package com.tth.learn.addproperties.java;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 比较对象大小的两个接口：Comparable、 Comparator
 * @Author tth
 * @Date 2022/12/7 17:07
 */
public class CompareTest {

    @Test
    public void comparableTest() {
        Goods[] goods = new Goods[4];
        goods[0] = new Goods("apple", 5.13);
        goods[1] = new Goods("basketball", 130.99);
        goods[2] = new Goods("bag", 999);
        goods[3] = new Goods("banana", 5.13);
        Arrays.sort(goods);

        System.out.println(Arrays.toString(goods));
    }

    @Test
    public void comparatorTest() {
        Goods[] goods = new Goods[4];
        goods[0] = new Goods("apple", 5.13);
        goods[1] = new Goods("basketball", 130.99);
        goods[2] = new Goods("bag", 999);
        goods[3] = new Goods("banana", 5.13);

        // 按照价格倒序排序。如果价格相等，按照商品名称倒序排序
        Arrays.sort(goods, new Comparator<Goods>() {
            @Override
            public int compare(Goods o1, Goods o2) {
                if (o1.getPrice() > o2.getPrice()) {
                    return -1;
                } else if (o1.getPrice() < o2.getPrice()) {
                    return 1;
                } else {
                    return -o1.getName().compareTo(o2.getName());
                }
            }
        });
        System.out.println(Arrays.toString(goods));
    }
}
